package com.wj.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wj.common.vo.SocialUser;
import com.wj.gulimall.member.dao.MemberLevelDao;
import com.wj.gulimall.member.entity.MemberLevelEntity;
import com.wj.gulimall.member.exception.PhoneExistException;
import com.wj.gulimall.member.exception.UsernameExistException;
import com.wj.gulimall.member.vo.MemberLoginVo;
import com.wj.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.common.utils.PageUtils;
import com.wj.common.utils.Query;

import com.wj.gulimall.member.dao.MemberDao;
import com.wj.gulimall.member.entity.MemberEntity;
import com.wj.gulimall.member.service.MemberService;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        String phone = vo.getPhone();
        String userName = vo.getUserName();
        checkPhoneUnique(phone);
        checkUsernameUnique(userName);

        memberEntity.setMobile(phone);
        memberEntity.setUsername(userName);
        memberEntity.setNickname(userName);

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer name = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (name > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity == null) {
            return null;
        } else {
            String pwd = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, pwd);
            if (matches) {
                return entity;
            }

        }
        return null;
    }

    /**
     * 使用RestTemplate的坑有点多
     */
    @Override
    public MemberEntity login(SocialUser user) {
        String uid = user.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //用户已经注册
            memberEntity.setExpiresIn(user.getExpires_in());
            memberEntity.setAccessToken(user.getAccess_token());
            updateById(memberEntity);
        } else {
            //尚未注册
            memberEntity = new MemberEntity();
            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setSocialUid(uid);
            memberEntity.setExpiresIn(user.getExpires_in());
            memberEntity.setLevelId(memberLevelDao.getDefaultLevel().getId());
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token", user.getAccess_token());
                map.put("uid", user.getUid());
                String url = "https://api.weibo.com/2/users/show.json?access_token={access_token}&uid={uid}";
                ResponseEntity<Object> response = restTemplate.getForEntity(url, Object.class, map);
                Map respMap = (LinkedHashMap) response.getBody();
                String name = (String) respMap.get("name");
                memberEntity.setNickname(name);
                memberEntity.setCity((String) respMap.get("location"));
                memberEntity.setGender("m".equals(respMap.get("gender")) ? 1 : 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            save(memberEntity);
        }

        return memberEntity;
    }

}